package zhuyun.code.launcheractivity.view

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import kotlinx.android.synthetic.main.activity_login_by_phone.*
import kotlinx.android.synthetic.main.et_img_hint.view.*
import kotlinx.android.synthetic.main.title_bar_base.*
import zhuyun.code.launcheractivity.App
import zhuyun.code.launcheractivity.R
import zhuyun.code.launcheractivity.model.Constants
import zhuyun.code.launcheractivity.model.NetworkRequest
import zhuyun.code.launcheractivity.model.ResponseDataHandler
import zhuyun.code.launcheractivity.model.data.BaseResponse
import zhuyun.code.launcheractivity.model.data.MobileLoginBean
import zhuyun.code.launcheractivity.model.db.UserInfo
import zhuyun.code.launcheractivity.model.db.UserInfo_
import zhuyun.code.launcheractivity.utils.EncoderData
import zhuyun.code.launcheractivity.utils.SPUtils

class LoginByPhoneActivity : BaseActivity(),View.OnClickListener {
    private var phoneNumberNotEmpty:Boolean = false
    private var passwordNotEmpty:Boolean = false
    private lateinit var popupWindow:PopupWindowLoginByPhoneNum

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login_by_phone)
        tvRight.text="切换语言"
        iv_back.setImageResource(R.drawable.btn_cancel_navibar)
        btLogin.isEnabled = false

        etHint_phone.et.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(p0: Editable?) {

            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                s?.let { phoneNumberNotEmpty = it.isNotEmpty()  }
                btLogin.isEnabled = phoneNumberNotEmpty&&passwordNotEmpty

            }

        })
        etHint_password.et.addTextChangedListener(object :TextWatcher{
            override fun afterTextChanged(p0: Editable?) {

            }

            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                s?.let { passwordNotEmpty = it.isNotEmpty()  }
                btLogin.isEnabled = phoneNumberNotEmpty&&passwordNotEmpty
            }

        })
        iv_back.setOnClickListener(this)
        tv_more.setOnClickListener(this)
        btLogin.setOnClickListener(this)
        btSign.setOnClickListener(this)
        popupWindow = PopupWindowLoginByPhoneNum(this)
        popupWindow.setOnDismissListener { backgroundAlpha(1.0f) }


    }

    override fun onClick(v: View?) {
        when(v?.id){
            R.id.iv_back->{ finish() }
            R.id.tv_more->{
                popupWindow.showAtLocation(tv_more, Gravity.BOTTOM, 0, 0)
                backgroundAlpha(0.7f)
            }
            R.id.btLogin->{
                NetworkRequest.mobileLogin(etHint_phone.et.text.toString().trim(),EncoderData.encoderByMd5(etHint_password.et.text.toString().trim()),
                    Constants.country_id, object :ResponseDataHandler<MobileLoginBean>(){
                        override fun onSuccess(
                            resultData: MobileLoginBean?,
                            baseResponse: BaseResponse<MobileLoginBean>
                        ) {
                            saveAccount(resultData)
                            startActivity(MainActivity::class.java)

                        }

                        override fun onFailure(errMsg: String?) {

                        }

                    })
            }
            R.id.btSign->{
                startActivity(SignInFirstActivity::class.java)
            }


        }
    }

    private fun saveAccount(mobileLoginBean: MobileLoginBean?){
        mobileLoginBean?.let {
            SPUtils.putBoolean(Constants.REMEMBERPSW,checkbox.isChecked)
            SPUtils.putBoolean(Constants.IS_LOGIN_BY_PHONE,true)
            SPUtils.putUserString(Constants.TOKEN, it.Token)
            SPUtils.putUserString(Constants.USER_ID,it.UserId)
            SPUtils.putBoolean(Constants.IS_MODIFY_ACCOUNT, it.IsModifyAccount)
            SPUtils.putUserBoolean(Constants.IS_LOGIN, true)
            SPUtils.putUserBoolean(Constants.IS_PAY_SET,it.IsPaySet)

            SPUtils.putString(Constants.TOKEN,it.Token)
            SPUtils.putString(Constants.USER_ID,it.UserId)
            SPUtils.putString(Constants.PHONE,etHint_phone.et.text.toString().trim())
            SPUtils.putString(Constants.USER_PASSWORD,etHint_password.et.text.toString().trim())
            SPUtils.putString(Constants.USER_NAME,it.UserName)
            SPUtils.putString(Constants.HEAD_URL,it.HeadUrl)

            val userInfoBox = App.context.boxStore.boxFor(UserInfo::class.java)
            val userIdList = userInfoBox.query().build().property(UserInfo_.userId).findStrings()
            val userId = SPUtils.getString(Constants.USER_ID,"")
            if(!userIdList.contains(userId)){
                val userInfo = UserInfo(
                    userId = userId,
                    nickname = mobileLoginBean.UserName,
                    headurl = mobileLoginBean.HeadUrl,
                    remarks = "",
                    icon = null,
                    notice = null,
                    ownerid = null,
                    shopId = null,
                    tid = null,
                    tname = null,
                    id = 0
                )
                userInfoBox.put(userInfo)
            }



        }



    }


}
